package com.tt5.services.vertx

import io.vertx.core.Vertx
import io.vertx.ext.web.Route
import io.vertx.ext.web.RoutingContext
import io.vertx.kotlin.coroutines.dispatcher
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch


/**
 * An extension method for simplifying coroutines usage with Vert.x Web routers
 */
@OptIn(DelicateCoroutinesApi::class)
fun Route.coroutineHandler(fn : suspend (RoutingContext) -> Unit): Route {
  val dispatcher = Vertx.currentContext().dispatcher()
  handler { ctx ->
    GlobalScope.launch(dispatcher) {
      try {
        fn(ctx)
      } catch(e: Exception) {
        ctx.fail(e)
      }
    }
  }
  return this
}
